<?php

namespace App\Jobs\Script;

use App\Models\Common\Wechat;
use App\Models\Tools\Data;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SendWechatMessage implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    private $template; // 模板name
    private $openid; // 接收人openid
    private $sender; // 推送人
    private $data; // 推送信息
    private $path; // 推送链接

    /**
     * Create a new job instance.
     * @param string $template 模板name
     * @param string $openid 接收人openid
     * @param int $sender 推送人
     * @param array $data 推送信息
     * @param string $path 推送链接
     */
    public function __construct(string $template,string $openid,int $sender,array $data = [],string $path = '')
    {
        $this->template = $template;
        $this->openid = explode(' ', $openid);
        $this->sender = $sender;
        $this->data = $data;
        $this->path = $path;
    }

    /**
     * Execute the job.
     * 发送微信模板消息
     *
     * @return void
     */
    public function handle()
    {
        Log::debug('手动推送模板消息开始');
        // data
        $template_data = Data::$wechat_blade_detail[$this->template];
        $data = [];
        foreach ($template_data as $key => $value) {
            $data[$key] = $this->data[$key] ?? '';
        }

        // 统计推送成功数量
        $total = count($this->openid);
        $success = 0;
        $failed = 0;
        $insert_array = [];

        $app = Wechat::officialAccount();

        foreach ($this->openid as $id) {
            try {
                $result = $app->template_message->send([
                    "touser" => $id,
                    "template_id" => Data::$wechat_blade[env('APP_ENV')][$this->template],
                    "url" => $this->path,
                    "data" => $data,
                ]);
                if ($result['errcode'] === 0) {
                    $success++;
                    $insert_array[] = [
                        'openid' => $id,
                        'success' => 1,
                    ];
                } else {
                    $failed++;
                    $insert_array[] = [
                        'openid' => $id,
                        'success' => 0,
                    ];
                    Log::error('公众号通知推送失败', $result);
                }
            } catch (\Exception $e) {
                Log::error(SendWechatMessage::class, ['msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()]);
            }
        }

        // 记录日志
        $data = json_encode($data);
        foreach($insert_array as &$insert){
            $insert['blade_name'] = $this->template;
            $insert['method'] = 'TemplateSendController';
            $insert['data'] = $data;
            $insert['path'] = $this->path;
            $insert['send_user'] = $this->sender;
        }
        unset($insert);
        DB::table('sys_template_log')->insert($insert_array);

        Log::debug('手动推送模板消息结束，本次推送总计：' . $total . '个，推送成功：' . $success . '个，推送失败：' . $failed . '个。');
        return;
    }
}
